/*
 * mem_functions.hpp
 *
 *  Created on: 7 Jan 2013
 *      Author: Asteroth
 */

#ifndef __MEM_FUNCTIONS_HPP__
#define __MEM_FUNCTIONS_HPP__

#define new_array(type, size) (new type[size])
#define delete_array(array) delete[] array

#define new_array2(type, size0, size1) __detail::_new_array((type*)0, size0, size1)
#define delete_array2(array) delete[] array[0]; delete[] array

#define new_array3(type, size0, size1, size2) __detail::_new_array((type*)0, size0, size1, size2)
#define delete_array3(array) delete[] array[0][0]; delete[] array[0]; delete[] array

namespace __detail {

template<typename T> inline T** _new_array(T* type, int size0, int size1) {
	T* values = new T[size0 * size1];
	T** array;
	try {
		array = new T*[size0];
	} catch (std::bad_alloc &e) {
		delete[] values;
		throw e;
	}
	for (int i = 0; i < size0; i++)
		array[i] = values + i * size1;
	return array;
}

template<typename T> inline T*** _new_array(T* type, int size0, int size1, int size2) {
	T** array2 = _new_array((T*)0, size0 * size1, size2);
	T*** array;
	try {
		array = new T**[size0];
	} catch (std::bad_alloc &e) {
		delete_array2(array2);
		throw e;
	}
	for (int i = 0; i < size0; i++) {
		array[i] = array2 + i * size1;
	}
	return array;
}

}

#endif /* __MEM_FUNCTIONS_HPP__ */
